package com.sx.admin.controller.plat;

import com.alibaba.fastjson.JSON;
import com.sx.admin.controller.BaseController;
import com.sx.admin.shiro.SecurityUserUtils;
import com.sx.core.model.Clazz;
import com.sx.core.model.Information;
import com.sx.core.mybatis.SessionTemplate;
import com.sx.core.page.Page;
import com.sx.core.utils.ExcelUtils;
import com.sx.core.utils.Md5;
import com.sx.core.utils.UUIDUtils;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.Params;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lihao on 2017/6/29.
 */
@RequestMapping("pl/info")
@RestController
public class InfoController extends BaseController {
    @Autowired
    SessionTemplate sessionTemplate;

    @RequestMapping("list_infos")
    public JsonReaderResponse list_order(@RequestParam Map<String,Object> params) {
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")),1);
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")),25);
        Page<Information> listPage=sessionTemplate.listPage(Information.class,"select_list",page,limit,params);
        return new JsonReaderResponse(listPage.getContent(),listPage.getTotalElements());
    }
    @RequestMapping("del_infos")
    public JsonReaderResponse del_infos(String id) {
        sessionTemplate.delete(Information.class,id);
        return new JsonReaderResponse();
    }
    @RequestMapping("save_infos")
    public JsonReaderResponse save_infos(Information clazz) {
        if(StringUtils.isEmpty(clazz.getId())){
            Information exist=sessionTemplate.get(Information.class,"selectBySno",new Params().p("sno",clazz.getSno()));
            if(exist!=null){
                return new JsonReaderResponse("学工号已存在",101);
            }

            clazz.setId(UUIDUtils.generateUuid32());
            clazz.setCreatedate(new Date());
            sessionTemplate.save(clazz);
        }else{
            Information exist=sessionTemplate.get(Information.class,"selectBySno",new Params().p("sno",clazz.getSno()));
            if(exist!=null && !exist.getId().equals(clazz.getId())){
                return new JsonReaderResponse("学工号已存在",101);
            }
            sessionTemplate.edit(clazz);
        }
        return new JsonReaderResponse();
    }

    @RequestMapping("list_class")
    public JsonReaderResponse list_class(@RequestParam Map<String,Object> params) {
        int page= NumberUtils.toInt(ObjectUtils.toString(params.get("page")),1);
        int limit= NumberUtils.toInt(ObjectUtils.toString(params.get("limit")),25);
        Page<Clazz> listPage=sessionTemplate.listPage(Clazz.class,"select_list",page,limit,params);
        return new JsonReaderResponse(listPage.getContent(),listPage.getTotalElements());
    }
    @RequestMapping("del_class")
    public JsonReaderResponse del_class(String id) {
        sessionTemplate.delete(Clazz.class,id);
        return new JsonReaderResponse();
    }
    @RequestMapping("save_class")
    public JsonReaderResponse del_class(Clazz clazz) {
        if(StringUtils.isEmpty(clazz.getId())){
            clazz.setId(UUIDUtils.generateUuid32());
            clazz.setCreatetime(new Date());
            sessionTemplate.save(clazz);
        }else{
            sessionTemplate.edit(clazz);
        }
        return new JsonReaderResponse();
    }

    @RequestMapping("import_class")
    public JsonReaderResponse batchffYs(@RequestParam Map<String,String> param_columns, MultipartFile file, HttpServletRequest request){
        String name_index=param_columns.get("name");
        String graduation_index=param_columns.get("graduation");


        Map<Integer,String> columns=new HashMap<>();
        columns.put(Integer.valueOf(name_index),"name");
        columns.put(Integer.valueOf(graduation_index),"graduation");

        List<Map<String,Object>> results=new ArrayList<>();
        List<Map<String,Object>> fail_results=new ArrayList<>();
        final int[] successCount = {0};
        final int[] failCount = { 0 };
        JsonReaderResponse response=new JsonReaderResponse();
        response.setMessage("数据读取异常");
        FileOutputStream os3=null;
        Workbook workbook3=null;
        InputStream is=null;
        String ext;
        try {
            is= file.getInputStream();
            ext="."+FilenameUtils.getExtension(file.getOriginalFilename());
        } catch (IOException e) {
            logger.error("import error",e);
            return new JsonReaderResponse("读取文件失败",101);
        }
        try {

            ExcelUtils.doImport(is,ext, 0,3, 30000,columns, new ExcelUtils.DoImportCallback(){
                @Override
                public void doImport(List<Map<String, Object>> list) {
                    int len=list.size();
                    for(int i=0;i<len;i++){
                        Map<String,Object> result=list.get(i);
                        try{
                            String name= ObjectUtils.toString(result.get("name")).trim();
                            String graduation= ObjectUtils.toString(result.get("graduation")).trim();

                            if(StringUtils.isEmpty(name)
                                    && StringUtils.isEmpty(graduation)
                                    ){
                                continue;
                            }
                            if(StringUtils.isEmpty(name) || StringUtils.isEmpty(graduation) ){
                                String des="必填项缺少数据，请检查";
                                result.put("des",des);
                                result.put("style","fail");
                                results.add(result);
                                failCount[0]++;
                                fail_results.add(result);
                                continue;
                            }
                            Clazz clazz=sessionTemplate.get(Clazz.class,"selectByName",new Params().p("name",name));
                            if(clazz!=null){
                                clazz.setName(name);
                                clazz.setGraduation(StringUtils.equals("是",graduation)?1:0);
                                sessionTemplate.edit(clazz);
                            }else{
                                clazz=new Clazz();
                                clazz.setCreatetime(new Date());
                                clazz.setId(UUIDUtils.generateUuid32());
                                clazz.setName(name);
                                clazz.setGraduation(StringUtils.equals("是",graduation)?1:0);
                                sessionTemplate.save(clazz);
                            }
                            successCount[0]++;
                        }catch (Exception e){
                            logger.error("import item error>>i="+i+">>json="+ JSON.toJSONString(result),e);
                            String des="导入异常";
                            result.put("des",des);
                            result.put("style","fail");
                            results.add(result);
                            failCount[0]++;
                            fail_results.add(result);
                            continue;
                        }
                    }


                }
            });
            if(failCount[0]>0){
                try{
                    String sheetName = "导入结果";String dir=new StringBuilder().append(uploadPath).append(File.separator).append(DateFormatUtils.format(new Date(), "yyyyMMdd")).append(File.separator).toString();
                    dir= FilenameUtils.normalize(dir);
                    File logFile=new File(dir);
                    if(!logFile.exists()){
                        logFile.mkdirs();
                    }
                    String str3         = System.currentTimeMillis()+"_fail"+".xlsx";
                    File failFile=new File(logFile,str3);
                    os3 = new FileOutputStream(failFile);
                    String fail_fail_txt="本次导入共"+(successCount[0]+failCount[0])+"条，失败："+failCount[0]+"条，详请如下";
                    workbook3 = ExcelUtils.export(sheetName,ExcelUtils.xlsx, logrows(fail_fail_txt), fail_results);
                    workbook3.write(os3);
                    os3.flush();
                    SecurityUserUtils.setSessionAttribute("Import_result",failFile.getAbsolutePath());
                }catch (Exception e){
                    logger.error("write log error");
                }
                return new JsonReaderResponse("导入失败",4000);
            }
            return new JsonReaderResponse();
        }finally {
            IOUtils.closeQuietly(os3);
            IOUtils.closeQuietly(workbook3);
        }
    }

    private ExcelUtils.Rows logrows(String fail_txt){
        ExcelUtils.Columns columns1 = new ExcelUtils.Columns();
        int index=0;
        ExcelUtils.Column r1_c0_0 = new ExcelUtils.Column(index++, "班级名称", 0, 0, "name", 6000);
        ExcelUtils.Column r1_c1_1 = new ExcelUtils.Column(index++, "是否毕业", 0, 0, "graduation",5000);
        ExcelUtils.Column r1_c5 = new ExcelUtils.Column(index++, "原因", 0, 0, "des", 15000);
        columns1.addColumn(r1_c0_0)
                .addColumn(r1_c1_1)
                .addColumn(r1_c5);


        ExcelUtils.Column r2_c1 = new ExcelUtils.Column(0, fail_txt, 0, 5, "","fail");
        ExcelUtils.Columns columns2 = new ExcelUtils.Columns();
        columns2.addColumn(r2_c1);
        ExcelUtils.Row row1 = new ExcelUtils.Row(1, columns1);
        ExcelUtils.Row row2 = new ExcelUtils.Row(2, columns2);
        ExcelUtils.Rows rows = new ExcelUtils.Rows();
        rows.addRow(row1).addRow(row2);
        return rows;
    }
    @RequestMapping("download/batch/result")
    public void exportStudent(HttpServletRequest request, HttpServletResponse response) {
        String history=(String) SecurityUserUtils.getSessionAttribute("Import_result");
        File file=null;
        if(history!=null && StringUtils.isNotBlank(history)){
            file=new File(history);
            if(!file.exists()){
                return;
            }
            download(file,request,response,"导入结果");
        }
    }
    @RequestMapping("import_infos")
    public JsonReaderResponse import_infos(@RequestParam Map<String,String> param_columns, MultipartFile file, HttpServletRequest request){
        final String type=param_columns.get("type");
        final String classid=param_columns.get("classid");


        String name_index=param_columns.get("name");
        String sno_index=param_columns.get("sno");
        String idno_index=param_columns.get("idno");
        String dept_index=param_columns.get("dept");
        String password_index=param_columns.get("password");
        String pid_index=param_columns.get("pid");
        String email_index=param_columns.get("email");
        String mobile_index=param_columns.get("mobile");
        String zy_index=param_columns.get("zy");


        Map<Integer,String> columns=new HashMap<>();
        columns.put(Integer.valueOf(name_index),"name");
        columns.put(Integer.valueOf(sno_index),"sno");
        columns.put(Integer.valueOf(idno_index),"idno");
        columns.put(Integer.valueOf(dept_index),"dept");
        columns.put(Integer.valueOf(password_index),"password");
        columns.put(Integer.valueOf(pid_index),"pid");
        columns.put(Integer.valueOf(email_index),"email");
        columns.put(Integer.valueOf(mobile_index),"mobile");
        columns.put(Integer.valueOf(zy_index),"zy");

        List<Map<String,Object>> results=new ArrayList<>();
        List<Map<String,Object>> fail_results=new ArrayList<>();
        final int[] successCount = {0};
        final int[] failCount = { 0 };
        JsonReaderResponse response=new JsonReaderResponse();
        response.setMessage("数据读取异常");
        FileOutputStream os3=null;
        Workbook workbook3=null;
        InputStream is=null;
        String ext;
        try {
            is= file.getInputStream();
            ext="."+FilenameUtils.getExtension(file.getOriginalFilename());
        } catch (IOException e) {
            logger.error("import error",e);
            return new JsonReaderResponse("读取文件失败",101);
        }
        try {

            ExcelUtils.doImport(is,ext, 0,3, 30000,columns, new ExcelUtils.DoImportCallback(){
                @Override
                public void doImport(List<Map<String, Object>> list) {
                    int len=list.size();
                    for(int i=0;i<len;i++){
                        Map<String,Object> result=list.get(i);
                        try{
                            String name= ObjectUtils.toString(result.get("name")).trim();
                            String sno= ObjectUtils.toString(result.get("sno")).trim();
                            String idno= ObjectUtils.toString(result.get("idno")).trim();
                            String dept= ObjectUtils.toString(result.get("dept")).trim();
                            String password= ObjectUtils.toString(result.get("password")).trim();
                            String pid= ObjectUtils.toString(result.get("pid")).trim();
                            String email= ObjectUtils.toString(result.get("email")).trim();
                            String mobile= ObjectUtils.toString(result.get("mobile")).trim();
                            String zy= ObjectUtils.toString(result.get("zy")).trim();

                            if(StringUtils.isEmpty(name)
                                    && StringUtils.isEmpty(sno)
                                    && StringUtils.isEmpty(idno)
                                    && StringUtils.isEmpty(dept)
                                    && StringUtils.isEmpty(password)
                                    && StringUtils.isEmpty(pid)
                                    && StringUtils.isEmpty(mobile)
                                    && StringUtils.isEmpty(email)
                                    && StringUtils.isEmpty(zy)
                                    ){
                                continue;
                            }
                            if(StringUtils.isEmpty(name) || StringUtils.isEmpty(sno) || StringUtils.isEmpty(password) ){
                                String des="必填项缺少数据，请检查";
                                result.put("des",des);
                                result.put("style","fail");
                                results.add(result);
                                failCount[0]++;
                                fail_results.add(result);
                                continue;
                            }
                            Information information=sessionTemplate.get(Information.class,"selectBySno",new Params().p("sno",sno));
                            if(information!=null){
                                information.setName(name);
                                information.setIdno(idno);
                                information.setDept(dept);
                                if(StringUtils.isEmpty(information.getPassword())){
                                    information.setPassword(Md5.md5(password));
                                }

                                information.setPid(pid);
                                information.setType(type);
                                information.setClassid(classid);
                                information.setEmail(email);
                                information.setMobile(mobile);
                                information.setZy(zy);
                                sessionTemplate.edit(information);
                            }else{
                                information=new Information();
                                information.setCreatedate(new Date());
                                information.setId(UUIDUtils.generateUuid32());
                                information.setName(name);
                                information.setType(type);
                                information.setSno(sno);
                                information.setIdno(idno);
                                information.setClassid(classid);
                                information.setDept(dept);
                                information.setPassword(Md5.md5(password));
                                information.setPid(pid);
                                information.setEmail(email);
                                information.setMobile(mobile);
                                information.setZy(zy);
                                sessionTemplate.save(information);
                            }
                            successCount[0]++;
                        }catch (Exception e){
                            logger.error("import item error>>i="+i+">>json="+ JSON.toJSONString(result),e);
                            String des="导入异常";
                            result.put("des",des);
                            result.put("style","fail");
                            results.add(result);
                            failCount[0]++;
                            fail_results.add(result);
                            continue;
                        }
                    }


                }
            });
            if(failCount[0]>0){
                try{
                    String sheetName = "导入结果";String dir=new StringBuilder().append(uploadPath).append(File.separator).append(DateFormatUtils.format(new Date(), "yyyyMMdd")).append(File.separator).toString();
                    dir= FilenameUtils.normalize(dir);
                    File logFile=new File(dir);
                    if(!logFile.exists()){
                        logFile.mkdirs();
                    }
                    String str3         = System.currentTimeMillis()+"_fail"+".xlsx";
                    File failFile=new File(logFile,str3);
                    os3 = new FileOutputStream(failFile);
                    String fail_fail_txt="本次导入共"+(successCount[0]+failCount[0])+"条，失败："+failCount[0]+"条，详请如下";
                    workbook3 = ExcelUtils.export(sheetName,ExcelUtils.xlsx, logrows_ino(fail_fail_txt,type), fail_results);

                    workbook3.write(os3);
                    os3.flush();
                    SecurityUserUtils.setSessionAttribute("Import_result",failFile.getAbsolutePath());
                }catch (Exception e){
                    logger.error("write log error");
                }
                return new JsonReaderResponse("导入失败",4000);
            }
            return new JsonReaderResponse();
        }finally {
            IOUtils.closeQuietly(os3);
            IOUtils.closeQuietly(workbook3);
        }
    }

    private ExcelUtils.Rows logrows_ino(String fail_txt,String type){
        ExcelUtils.Columns columns1 = new ExcelUtils.Columns();
        int index=0;
        ExcelUtils.Column r1_c0_0 = new ExcelUtils.Column(index++, "学工号", 0, 0, "sno", 6000);
        ExcelUtils.Column r1_c1_1 = new ExcelUtils.Column(index++, "姓名", 0, 0, "name",5000);
        ExcelUtils.Column r1_c1_2 = new ExcelUtils.Column(index++, "初始密码", 0, 0, "password",5000);
        ExcelUtils.Column r1_c1_3_ = new ExcelUtils.Column(index++, "身份证号", 0, 0, "idno",5000);
        ExcelUtils.Column r1_c1_3 = new ExcelUtils.Column(index++, "电子邮件", 0, 0, "email",5000);
        ExcelUtils.Column r1_c1_4 = new ExcelUtils.Column(index++, "联系电话", 0, 0, "mobile",5000);
        ExcelUtils.Column r1_c1_5 = new ExcelUtils.Column(index++, "专业", 0, 0, "zy",5000);
        ExcelUtils.Column r1_c1_6 = new ExcelUtils.Column(index++, "部门", 0, 0, "dept",5000);
        ExcelUtils.Column r1_c1_7 = new ExcelUtils.Column(index++, "身份/职位", 0, 0, "pid",5000);
        ExcelUtils.Column r1_c5 = new ExcelUtils.Column(index++, "原因", 0, 0, "des", 15000);
        if(StringUtils.equals(type,"1")){
            columns1.addColumn(r1_c0_0)
                    .addColumn(r1_c1_1)
                    .addColumn(r1_c1_2)
                    .addColumn(r1_c1_3_)
                    .addColumn(r1_c1_3)
                    .addColumn(r1_c1_4)
                    .addColumn(r1_c1_5)
                    .addColumn(r1_c5);
        }else{
            columns1.addColumn(r1_c0_0)
                    .addColumn(r1_c1_1)
                    .addColumn(r1_c1_2)
                    .addColumn(r1_c1_3_)
                    .addColumn(r1_c1_3)
                    .addColumn(r1_c1_4)
                    .addColumn(r1_c1_5)
                    .addColumn(r1_c1_6)
                    .addColumn(r1_c1_7)
                    .addColumn(r1_c5);
        }


        ExcelUtils.Column r2_c1 = new ExcelUtils.Column(0, fail_txt, 0, 5, "","fail");
        ExcelUtils.Columns columns2 = new ExcelUtils.Columns();
        columns2.addColumn(r2_c1);
        ExcelUtils.Row row1 = new ExcelUtils.Row(1, columns1);
        ExcelUtils.Row row2 = new ExcelUtils.Row(2, columns2);
        ExcelUtils.Rows rows = new ExcelUtils.Rows();
        rows.addRow(row1).addRow(row2);
        return rows;
    }











}
